package com.kpl.kplstzble.fragment;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import com.kpl.kplstzble.R;
import com.kpl.kplstzble.activity.HomeActivity;
import com.kpl.kplstzble.downkplfile.HttpDownloader;
import com.kpl.kplstzble.utils.BleHelper;
import com.kpl.kplstzble.utils.CirclePgBar;
import com.kpl.kplstzble.utils.DataTrasportUtil;
import com.kpl.kplstzble.utils.FileChooseUtil;
import com.kpl.kplstzble.utils.JschUtil;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;

public class UpgradationFragment extends Fragment {
    //文件路径前缀
   // private String propath = "/storage/emulated/0/assets/";
    private View mapLayout;
    private Button refresh;
    private Button sureupload;
    private Button redownload;
    //private  Button localupload;
    //发送文件信息失败次数
    public static Integer revfilemesfailnum;
    //发送文件数据失败次数
    public static Integer revfiledatafailnum;
    //发送传输结束失败次数
    public static Integer revoverfailnum;
    //升级数据包序号
    public static Integer dataorder = 0;

    //一个升级文件分帧数
    public static Integer filedatanum;

    //最后一帧数据长度
    public static Integer lastdatanum;
    //第几个循环（帧数超过255循环加1）
    public static Integer circorder;

    public static BufferedInputStream bis;
    private Spinner mySpinner0;

    //下拉框
    private Spinner mySpinner1;

    private TextView uploadstatus;
    //当前状态
    public static TextView  uploadlog;

    //当前升级文件类型
    //0x00:完整升级文件(update.bin)  0
    //0x01:资源文件(rom.bin)  1
    //0x02:动画文件(bootanim.bin)  2
    //0x03:应用文件(amt630h.bin)  3
    //0x04:loader 文件(spildr.bin)  4
    //0x05:stepldr 文件(stepldr.bin)  5
    public static Integer fileType = 3;
    public static Integer datalength = 128;
    //选择文件路径
    private String path;
    public static CirclePgBar circlePgBar;
    //加载框
    private ProgressDialog progressDialog;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mapLayout = inflater.inflate(R.layout.upgradation, null);
        startcheck();
        return mapLayout;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void startcheck() {
        uploadstatus = (TextView) mapLayout.findViewById(R.id.uploadstatus);
        uploadstatus.setText("进入升级模式！");

        uploadlog = (TextView) mapLayout.findViewById(R.id.uploadlog);
        uploadlog.setText("待升级！");
        Toast.makeText(getActivity(), "进入升级模式", Toast.LENGTH_LONG).show();
        initView();
        progressDialog = new ProgressDialog(getContext());
        //progressDialog.show();
        mySpinner0 =  mapLayout.findViewById(R.id.spinner0);
        mySpinner1 =  mapLayout.findViewById(R.id.spinner1);
        spinnerset();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView() {
        circlePgBar = mapLayout.findViewById(R.id.circlepgbar);
        refresh = mapLayout.findViewById(R.id.refresh);
        refresh.setOnClickListener(v-> spinner0set());
        sureupload = mapLayout.findViewById(R.id.sureupload);
        //redownload = mapLayout.findViewById(R.id.redownload);
        sureupload.setOnClickListener(v -> {
            revfilemesfailnum = 0;
            revfiledatafailnum = 0;
            revoverfailnum = 0;
            sureupload.setEnabled(false);
            uploadstatus.setText("正在升级中，请勿进行其他操作！");
            String bcc = yiHuo("81C60100");
            //write("5581C60100"+ bcc);
            String finalbcc = bcc;
            write("5581C60100"+ bcc);
            uploadlog.setText("发送'开始升级指令后'，待收到回复！");
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void spinnerset() {
        if(HomeActivity.lastfolder!=null&&HomeActivity.lastfile!=null){
            // 定义 Spinner 的列表数据
            String[] options = {HomeActivity.lastfolder};
            // 创建 ArrayAdapter，设置下拉菜单项的布局和数据
            ArrayAdapter<String> adapter0 = new ArrayAdapter<String>(getContext(),
                    android.R.layout.simple_spinner_dropdown_item, options);
            adapter0.setDropDownViewResource(
                    android.R.layout.simple_spinner_dropdown_item);
            mySpinner0.setAdapter(adapter0);
            mySpinner0.setSelection(0);

            // 定义 Spinner 的列表数据
            String[] options1 = {HomeActivity.lastfile};
            // 创建 ArrayAdapter，设置下拉菜单项的布局和数据
            ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getContext(),
                    android.R.layout.simple_spinner_dropdown_item, options1);
            adapter1.setDropDownViewResource(
                    android.R.layout.simple_spinner_dropdown_item);
            mySpinner1.setAdapter(adapter1);
            mySpinner1.setSelection(0);

            /*mySpinner0.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    progressDialog.show();
                    new Thread(() -> {
                        ArrayList<String> folders= JschUtil.getFolders0();
                        Message msg = new Message();
                        msg.obj = folders;
                        msg.what=3;
                        uiHandler.sendMessage(msg);
                    }
                    ).start();
                    return false;
                }
            });*/


        }else {
            spinner0set();
        }


    }
    private void spinner0set() {

            progressDialog.show();
            new Thread(() -> {
                ArrayList<String> folders= JschUtil.getFolders0();
                Message msg = new Message();
                msg.obj = folders;
                msg.what=3;
                uiHandler.sendMessage(msg);
            }
            ).start();
    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void spinner1set() {
        progressDialog.show();
        new Thread(() -> {
            String folder = mySpinner0.getSelectedItem().toString();
            ArrayList<String> folders= JschUtil.getFolders1(folder);
            Message msg = new Message();
            msg.obj = folders;
            msg.what=4;
            uiHandler.sendMessage(msg);
        }
        ).start();
    }

    //写入数据操作
    public static void write(String dataString) {
        BleHelper.sendCommand(HomeActivity.bluetoothGatt, dataString, "010200".equals(dataString));
    }

    public static HashMap<String, String> ParaseClientData(String revdata) {
        if (revdata.length() == 14) {
            HashMap<String, String> result = new HashMap<>();
            //判断校验
            //BCC前数据
            String bccdata = revdata.substring(2, 12);
            //计算BCC
            String getbcc = yiHuo(bccdata);
            //获取到的bcc
            String revbcc = revdata.substring(12, 14);
            if (getbcc.equals(revbcc)) {//校验通过
                //标识应答帧的类型 0x00：开始升级 0x01：文件信息 0x02：文件传输 0x03：传输结束
                String type = revdata.substring(8, 10);
                //表示返回的结果 0x00：ACK FAIL 0x01：ACK OK
                String rev = revdata.substring(10, 12);
                result.put("type", type);
                result.put("rev", rev);
            } else {
                //BCC校验失败
                System.out.println("校验失败");
            }
            return result;
        } else {
            System.out.println("数据不正常：" + revdata);
        }
        return null;
    }

    /**
     * BCC数据校验 异或处理
     */
    public static String yiHuo(String content) {
       /* int a = 0;
        for (int i = 0; i < content.length() / 2; i++) {
            a = a ^ Integer.parseInt(content.substring(i * 2, (i * 2) + 2), 16);
        }
        String result = Integer.toHexString(a);
        if (result.length() == 1) {
            return "0" + result;
        } else {
            return result;
        }*/
        byte[] bytes = DataTrasportUtil.HexString2Bytes(content);
        byte b = calculateChecksum(bytes);
        return DataTrasportUtil.byteToHex(b);
    }

    /**
     * 异或校验
     */
    private static byte calculateChecksum(byte[] data) {
        byte checksum = 0;
        for (byte b : data) {
            checksum ^= b;
        }
        return checksum;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println(152555);
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            if ("file".equalsIgnoreCase(uri.getScheme())) {//使用第三方应用打开
                path = uri.getPath();
                Log.d("queryfilepath", "返回结果1: " + path);
                return;
            }
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
                path = FileChooseUtil.getPath(getActivity(), uri);
                Log.d("queryfilepath", "返回结果2: " + path);

            } else {//4.4以下下系统调用方法
                path = FileChooseUtil.getRealPathFromURI(uri);
                Log.d("queryfilepath", "返回结果3: " + path);
            }
            System.out.println(14848);
            try {
                System.out.println("升级文件路径1"+path);
                File file = new File(path);
                long fileSize = file.length();
                filedatanum = (int) (fileSize % 128 == 0 ? fileSize / 128 : fileSize / 128 + 1);
                lastdatanum = (int) (fileSize % 128 == 0 ? 128 : fileSize % 128);
                FileInputStream fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    //读取128字节数据
    public static String readupgrade() {//传入第几帧
        //System.out.println("组帧长度" + datalength);
        String result = "";
        try {
            byte[] result2 = new byte[datalength];
            bis.read(result2);
            result = DataTrasportUtil.bytes2hexStr(result2);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    //读取128字节数据
    public static String readupgradelast() {//传入第几帧
        //System.out.println("组帧长度" + datalength);
        String result = "";
        try {
            byte[] result2 = new byte[lastdatanum];
           /* if(circorder==1&&dataorder==0){

            }else {
                bis.skip(datalength);
            }*/

            bis.read(result2);
            result = DataTrasportUtil.bytes2hexStr(result2);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    //发送文件数据
    public static void sendfiledata() {
        if (dataorder == 256) {
            dataorder = 0;
            circorder++;
        }
        //更新进度条
        int progress = ((circorder - 1) * 256 + dataorder)*100 / filedatanum;
        circlePgBar.add(progress+1);
        System.out.println("第" + circorder + "个循环");
        //继续发送数据
        String dataorderhex = Integer.toHexString(dataorder);
        System.out.println("第" + dataorder + "帧");
        if (dataorderhex.length() == 1) {
            dataorderhex = "0" + dataorderhex;
        }
        String readupgrade = readupgrade();
        String data = "81C68202" + dataorderhex + readupgrade;
        String bcc = yiHuo(data);
        //发送文件数据
        String senddata = "55" + data + bcc;
        write(senddata);
    }

    //发送文件数据
    public static void sendlastfiledata() {
        if (dataorder == 256) {
            dataorder = 0;
            circorder++;
        }
        System.out.println("第" + circorder + "个循环");
        //继续发送数据
        String dataorderhex = Integer.toHexString(dataorder);
        System.out.println("最后第" + dataorder + "帧");
        if (dataorderhex.length() == 1) {
            dataorderhex = "0" + dataorderhex;
        }
        int lastdatalen = lastdatanum + 2;
        String lastdatalenhex = Integer.toHexString(lastdatalen);
        if (lastdatalenhex.length() == 1) {
            lastdatalenhex = "0" + lastdatalenhex;
        }
        String readupgradelast = readupgradelast();
        String data = "81C6" + lastdatalenhex + "02" + dataorderhex + readupgradelast;
        String bcc = yiHuo(data);
        //发送文件数据
        String senddata = "55" + data + bcc;
        write(senddata);
    }

    private final Handler uiHandler = new Handler() {
        public void handleMessage(Message msg) {

            if (msg.what == -1) {
                progressDialog.dismiss();
                Toast.makeText(getActivity(), "未知错误，下载失败", Toast.LENGTH_SHORT).show();
            } else if (msg.what == 0) {
                progressDialog.dismiss();
                try {
                    System.out.println("升级文件路径2000"+HomeActivity.propath +"/"+ msg.obj+"/amt630h.bin");
                    File file = new File(HomeActivity.propath +"/"+ msg.obj+"/amt630h.bin");
                    long fileSize = file.length();
                    filedatanum = (int) (fileSize % 128 == 0 ? fileSize / 128 : fileSize / 128 + 1);
                    System.out.println("一个升级文件分帧数100"+filedatanum);
                    lastdatanum = (int) (fileSize % 128 == 0 ? 128 : fileSize % 128);
                    FileInputStream fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                String filename0 = mySpinner0.getSelectedItem().toString();
                String filename = mySpinner1.getSelectedItem().toString();
                HomeActivity.lastfolder=filename0;
                HomeActivity.lastfile=filename;
                Toast.makeText(getActivity(), msg.obj + "文件下载成功,请点击确认升级", Toast.LENGTH_SHORT).show();
            } else if (msg.what == 1) {
                progressDialog.dismiss();
                try {
                    System.out.println("升级文件路径2"+HomeActivity.propath +"/"+ msg.obj+"/amt630h.bin");
                    File file = new File(HomeActivity.propath +"/"+ msg.obj+"/amt630h.bin");
                    long fileSize = file.length();
                    filedatanum = (int) (fileSize % 128 == 0 ? fileSize / 128 : fileSize / 128 + 1);
                    System.out.println("一个升级文件分帧数1"+filedatanum);
                    lastdatanum = (int) (fileSize % 128 == 0 ? 128 : fileSize % 128);
                    FileInputStream fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                String filename0 = mySpinner0.getSelectedItem().toString();
                String filename = mySpinner1.getSelectedItem().toString();
                HomeActivity.lastfolder=filename0;
                HomeActivity.lastfile=filename;
                Toast.makeText(getActivity(), msg.obj + "文件已经存在,请点击确认升级", Toast.LENGTH_SHORT).show();
            } else if (msg.what == 2) {
                progressDialog.dismiss();
                Toast.makeText(getActivity(), msg.obj + "文件下载失败,请检查网络后重新连接升级" + msg.arg1, Toast.LENGTH_SHORT).show();
            }else if (msg.what == 3) {
                //progressDialog.dismiss();
                ArrayList<String> typelist = (ArrayList<String>) msg.obj;
                /*if(typelist.size()==0){
                    if (HomeActivity.lastselected==null){
                        Toast.makeText(getActivity(), "请检查网络后重新连接升级" + msg.arg1, Toast.LENGTH_SHORT).show();
                        typelist.add("请检查网络!jiaoc");
                    }else {
                        typelist.add(HomeActivity.lastselected);
                    }
                }*/

                ArrayAdapter<String> adapter0 = new ArrayAdapter<String>(getContext(),
                        android.R.layout.simple_spinner_dropdown_item, (ArrayList) typelist);
                adapter0.setDropDownViewResource(
                        android.R.layout.simple_spinner_dropdown_item);
                mySpinner0.setAdapter(adapter0);
                mySpinner0.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @RequiresApi(api = Build.VERSION_CODES.M)
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        spinner1set();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                        System.out.println("2" + mySpinner0.getSelectedItem());
                    }
                });

            }else if (msg.what == 4) {
                progressDialog.dismiss();
                ArrayList<String> typelist = (ArrayList<String>) msg.obj;
               /* if(typelist.size()==0){
                    if (HomeActivity.lastselected==null){
                        Toast.makeText(getActivity(), "请检查网络后重新连接升级" + msg.arg1, Toast.LENGTH_SHORT).show();
                        typelist.add("请检查网络!jiaoc");
                    }else {
                        typelist.add(HomeActivity.lastselected);
                    }
                }*/

                ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),
                        android.R.layout.simple_spinner_dropdown_item, (ArrayList) typelist);
                adapter.setDropDownViewResource(
                        android.R.layout.simple_spinner_dropdown_item);
                mySpinner1.setAdapter(adapter);
                mySpinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        // String filename = mySpinner.getSelectedItem().toString().split("-->")[1];
                        progressDialog.show();
                        String filename0 = mySpinner0.getSelectedItem().toString();
                        String filename = mySpinner1.getSelectedItem().toString();
                      /*  if(!filename.startsWith("请检查网络")){
                            HomeActivity.lastselected=filename;
                        }*/

                        //应用文件
                        fileType=3;
                        String realpath = HomeActivity.propath.split("emulated/0/")[1]+"/"+filename+"/";
                        new Thread(() -> {
                            HttpDownloader httpDownloader = new HttpDownloader();
                            int result = httpDownloader.downloadFile(
                                    "http://39.107.104.228:888/download/stzfile1/"+filename0+"/"+filename+"/amt630h.bin", realpath,  "amt630h.bin");

                            Message msg = new Message();
                            msg.obj = filename;
                            System.out.println("result:1"+result);
                            if (result == -1) {
                                msg.what = -1;
                            } else if (result == 0) {
                                msg.what = 0;
                            } else if (result == 1) {
                                msg.what = 1;
                            } else {
                                msg.what = 2;
                                msg.arg1 = result;
                            }
                            uiHandler.sendMessage(msg);
                        }).start();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                        System.out.println("2" + mySpinner1.getSelectedItem());
                    }
                });
            }
        }
    };
}
